'''
    序列化器
'''
from rest_framework import serializers
from books.models import BookInfo,HeroInfo

# 序列化器
class BookInfo1Serializer(serializers.Serializer):
    title = serializers.CharField()
    reader = serializers.CharField()

# 反序列化器
class BookInfo2Serializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=20,required=True,error_messages={"allow_null":"the is not null"},allow_null=True)
    reader = serializers.CharField(max_length=20)

    def validate_title(self,value):  #
        """
        局部数据验证 方法名必须是validate_<字段名> 为名称，否则序列化器不识别
        会自动被is_valid() 方法调用
        """

        # print(value)
        if value in ['python','django']:
            raise serializers.ValidationError("题目不能包含django,python",code='validate_title')

        return value


    def validate(self, attrs):

        # 观看python的人 等于100
        if attrs['title'] =="长江七号" and int(attrs['reader']) <= 100:
            raise serializers.ValidationError('长江七号观看的人太少了',code='validate')
        return attrs

    def create(self, validated_data):
        data = BookInfo.objects.create(**validated_data)
        # print(1)
        return data

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title',instance.title)
        instance.reader = validated_data.get('reader',instance.reader)
        instance.save()
        return instance


class HeroInfoSerializer(serializers.Serializer):
    # 定义数据来源表的名称
    name = serializers.CharField(max_length=20,label='名字')
    # bookid = serializers.PrimaryKeyRelatedField(label='描述信息',queryset=BookInfo.objects.all())  # 根据外键来进行绑定信息或字段
    # bookid = serializers.StringRelatedField(label='描述信息')  # 根据 models.py def __str__(self): return self.字段名  返回的信息 进行绑定
    bookid = serializers.SlugRelatedField(label='描述信息',slug_field="title",read_only=True)  # slug_field 进行字段绑定，read_only = True 只读
    # bookid = BookInfoSerializer() # 绑定一组序列化的数据


# 模型序列化器
class BookInfoModelSerializer(serializers.ModelSerializer):
    # 1. 声明字段
    # 字段名 = serialzers.字段类型(选项 = 选项值)
    # 也可以定义，模型里面没有的字段，需要额外声明字段
    # nickname = serializers.CharField(read_only=True)

    # 2. 声明模型
    class Meta:
        model = BookInfo   # 必填
        fields = ["id","title","reader"]  # 必填 也可以是字符串和列表/元组，字符串的值只能是"__all__"

        # read_only_fields = [] # 选填，只读字段列表，表示设置这里的字段只会在序列化阶段采用
        # extra_kwargs = {  # 选填，字段额外选项声明
        #       '字段':{
        #           "选项":"选项值"
        #       }
        # }
        extra_kwargs = {  # 选填，字段额外选项声明
            'reader': {
                "required": False,
                "error_messages": {
                    "required": "reader字段不能为空"
                }
              },

            }

    # 3. 验证代码的对象方法
    # def create(self, validated_data):
        # 密码加密
        # validated_data["password"] = make_password(validated_data["password"])
        # super().create(validated_data)

    # 4. 模型操作方法

